import React, { Component } from 'react'
import {
  Container,
  Row,
  Col,
  Image,
  ListGroup,
  Button,
  Badge, Alert,
  Spinner,
  Toast
} from 'react-bootstrap'
import intl from 'react-intl-universal'
import EvaluationItem from './EvaluationItem/EvaluationItem'
import { httpPost } from '../../../services/http'
import { connect } from 'react-redux'
import { isEmpty } from 'lodash'
import InputNumber from '../../../components/InputNumber/InputNumber'
import './DetailView.less'
import GoBack from '../../../components/GoBack/GoBack'

class DetailView extends Component {
  constructor (props) {
    super(props)

    this.state = {
      flag: false,
      spinnerShow: false,
      toastShow: false,
      toastContent: null
    }
    this.inputNumberRef = React.createRef()
  }

  componentDidMount () {
    // !这里获取不到 因为第一次的render函数flag为false并没有渲染元素  没有创建元素也就挂载不到ref
    // console.log(this.inputNumberRef.current, '获取ref')
    this.setIntl()
  }

  setIntl = () => {
    const { detail } = this.props
    const zh = {
      [detail.enTitle]: detail.zhTitle,
      [detail.enDescription]: detail.zhDescription,
      [detail.enPrice]: detail.zhPrice
    }
    const en = {
      [detail.enTitle]: detail.enTitle,
      [detail.enDescription]: detail.enDescription,
      [detail.enPrice]: detail.enPrice
    }
    intl.load({
      'zh-CN': zh,
      'en-US': en
    })
    this.setState({ flag: true })
  }

  // TODO 这里的业务逻辑应该是加入购物车的物品数量不能超过库存也不能小于1 但是我这里只是限制了单次的添加购物车物品数量
  // TODO 如果多次添加购物车并且累计数量超过库存,那么会成功 !应该进行改良!
  handleAddCart = async () => {
    const { detail, user } = this.props
    this.setState({ spinnerShow: true })
    if (isEmpty(user)) {
      this.setState({ toastShow: true, toastContent: intl.get('p login') })
    } else {
      const [res, err] = await httpPost({
        url: '/cart/addCart', data: {
          gid: detail._id,
          goods_num: this.inputNumberRef.current.state.num
        }
      })
      if (res) {
        this.setState(
          {
            toastShow: true,
            spinnerShow: false,
            toastContent: intl.get('add cart success')
          })
        console.log(res, '添加购物车成功')
      } else {
        this.setState(
          {
            toastShow: true,
            spinnerShow: false,
            toastContent: intl.get('add cart fail')
          })
        console.log(err, '添加购物车失败')
      }
    }
  }

  render () {
    const { detail } = this.props
    const { flag, toastShow, toastContent, spinnerShow } = this.state
    return (
      flag && <Container id = {'detail-view'}>
        {/* goback */}
        <Row><Col><GoBack /></Col></Row>
        {/* 商品详情 */}
        <Row>
          {/* 图片 */}
          <Col lg = {6}><Image src = {detail.big_img} fluid /></Col>
          {/* 详情介绍 */}
          <Col lg = {3}>
            <ListGroup variant = "flush">
              <ListGroup.Item>
                <h2>{intl.get(detail.enTitle)}</h2>
              </ListGroup.Item>
              <ListGroup.Item>
                <span>
                  {intl.get('detail.price')}:{intl.get('$')}
                  {intl.get(detail.enPrice)}
                </span>
              </ListGroup.Item>
              <ListGroup.Item>
                <span>
                  {intl.get('detail.description')}:
                  {intl.get(detail.enDescription)}
                </span>
              </ListGroup.Item>
            </ListGroup>
          </Col>
          {/* 价格状态 */}
          <Col lg = {3}><ListGroup>
            <ListGroup.Item>
             <span> {intl.get('detail.price')}:
               {intl.get('$')}{intl.get(detail.enPrice)}
             </span>
            </ListGroup.Item>
            <ListGroup.Item>
              <span>
                 {intl.get('detail.status')}:
               <Badge variant = "info">
                  {detail.inventory > 0 ? detail.inventory : intl.get(
                    'detail.run out')}
               </Badge>
              </span>
            </ListGroup.Item>
            <ListGroup.Item>
              <span>{intl.get('detail.count')}:</span>
              {/* 数字输入框组件 */}
              <InputNumber maxNum = {detail.inventory}
                           ref = {this.inputNumberRef} />
            </ListGroup.Item>
            <ListGroup.Item className = {'text-center'}>
              <Button onClick = {this.handleAddCart} disabled = {spinnerShow}>
                {spinnerShow &&
                <Spinner animation = "border" role = "status" size = "sm" />}
                {intl.get('detail.add to cart')}
              </Button>
            </ListGroup.Item>
          </ListGroup></Col>
        </Row>
        {/* reviews标题 */}
        <Row>
          <Col>
            <h2>{intl.get('detail.reviews')}</h2>
          </Col>
        </Row>
        {/* 评论 */}
        <Row>
          <Col lg = {6}>
            {
              detail.evaluations.length ?
                <ListGroup variant = {'flush'}>
                  {
                    detail.evaluations.map((ele, index) => {
                      return <EvaluationItem evaluation = {ele}
                                             key = {ele._id} />
                    })
                  }
                </ListGroup> : <Alert variant = {'info'}><h3>no reviews</h3>
                </Alert>
            }
          </Col>
        </Row>
        <Toast className = {'my-toast'} delay = {3000}
               show = {toastShow} autohide
               onClose = {() => this.setState({ toastShow: false })}>
          <Toast.Body>
            {toastContent}
          </Toast.Body>
        </Toast>
      </Container>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    user: state.user
  }
}

export default connect(mapStateToProps)(DetailView)
